<?php

class UCCASS_EncuestaPuntaje extends UCCASS_Main
{
  function UCCASS_EncuestaPuntaje()
    { $this->load_configuration(); }
  
  
  function elegir_accion($sid)
  {
    $query = "SELECT 1 FROM {$this->CONF['db_tbl_prefix']}answer_types WHERE name='Default' and sid=$sid";
                    
    //le pasa el dato si existe si hay una encuesta con ese nombre le pasa 1(uno) sino no le pasa nada
    
    $rs = $this->Query($query,'Unable to see if survey name matches another');
              
	//verifica si hay respuestas, sino redirecciona en este if extrae la primera fila si tuviera mas datos
	if($rs->FetchRow($rs))
    {  
       $query = "SELECT 1 FROM {$this->CONF['db_tbl_prefix']}grupos WHERE sid=$sid";
       
       //le pasa el dato si existe si hay una encuesta con ese nombre le pasa 1(uno) sino no le pasa nada
       $rs = $this->Query($query,'Unable to see if survey name matches another');
       //verifica si hay grupos, edita, sino crea
       if($rs->FetchRow($rs))
       { 
       	return $this->editar_grupos($sid);	}
       else
       { return $this->nuevos_grupos($sid); }
       
    }
    else
    {//enviar mensaje que primero debe haber alguna respuesta llenada con puntaje debe solo mostrar el mensaje arriba 
       $error= "Ingrese Primero sus preguntas con sus respectivas respuestas, luego agregue puntaje";
       $this->puntaje_error($error,"question_edit_survey.php?sid=$sid&mode=questions",'Error',2);
	}
  }
  
    
  function editar_grupos($sid)
  {   
        if(!$this->_CheckLogin("edit_answer.php?sid=$sid"))
        { return $this->showLogin('edit_survey.php',array('sid'=>$sid)); }
        
       

        $sid = (int)$sid;
        $data['puntajeMin'] = $this->puntaje_min_max('min',$sid);
        $data['puntajeMax'] = $this->puntaje_min_max('max',$sid);
        
        /*$qid = (int)$qid;
        $aid = (int)$aid;

		$query1 = "SELECT q.qid, q.aid, q.sid , at.name
		 FROM {$this->CONF['db_tbl_prefix']}questions q 
		 inner join {$this->CONF['db_tbl_prefix']}answer_types at on at.aid=q.aid
		 WHERE q.qid = $qid";
		
        $rs = $this->db->Execute($query1);
        
		
		if($rs === FALSE)
        { $this->error("Error getting answer detail: " . $this->db->ErrorMsg()); return; }
        $r = $rs->FetchRow($rs);
		
		if($r["aid"] === "0")
        {
        	$this->setMessageRedirect('add_answer.php?sid='.$r['sid'].'&mode=questions&qid='.$r['qid']);
		 	$this->setMessage('Notice','Question must have answers. Please insert or choose answers',MSGTYPE_NOTICE);
        }
		 
		
		if($r['name'] != 'Default')
        {
			$this->setMessageRedirect('edit_answer_type_choose.php?sid='.$r['sid'].'&mode=questions&qid='.$r['qid'].'&aid='.$r['aid']);
		 	$this->setMessage('&nbsp;','Escoger respuesta predeterminada',MSGTYPE_NOTICE);
		}
		
        $error = '';
        $show = array();
        $show['warning'] = FALSE;*/
        $load_answer = TRUE;

      
        /*$input['value'] = array();
        $input['numeric_value'] = array();
        $input['num_answers'] = 6;*/
        $input['show_add_answers'] = TRUE;
       /* $input['delete_avid'] = array();
        $input['sid'] = $sid;
		$input['qid'] = (int)$qid;
        $input['allowable_images'] = $this->get_image_names();

        $show['admin_link'] = FALSE;
        $show['delete'] = FALSE;

        $query = "SELECT COUNT(aid) AS c FROM {$this->CONF['db_tbl_prefix']}questions WHERE aid = $aid AND sid = $sid";

        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error("Error getting survey count: " . $this->db->ErrorMsg()); return; }
        $r = $rs->FetchRow($rs);
        if($r['c'] > 0)
        {
            $show['warning'] = TRUE;
            $this->smarty->assign('num_usedanswers',$r['c']);
            if($r['c'] > 1)
            { $this->smarty->assign('usedanswers_plural','s'); }
        }
        else
        { $show['delete'] = TRUE; }*/

       
	
		if(isset($_REQUEST['submit']) || isset($_REQUEST['add_answers_submit']))
        {
            $error = '';
            $load_answer = FALSE;
		
			if(isset($_REQUEST['add_answers_submit']))
            { $ss_type = SAFE_STRING_TEXT; }
            else
            { $ss_type = SAFE_STRING_DB; }

           

           // $input['aid'] = (int)$_REQUEST['aid'];

            $new_answer_count = 0;

           
            if(isset($_REQUEST['value']) && is_array($_REQUEST['value']) &&
               isset($_REQUEST['puntaje_min_value']) && is_array($_REQUEST['puntaje_min_value']) &&
               isset($_REQUEST['puntaje_max_value']) && is_array($_REQUEST['puntaje_max_value']) &&
               count($_REQUEST['value']) <= 99)
            {
            	
                        $input['num_answers'] = min(99,count($_REQUEST['value']));
						
                        $i=0;
						//$input['a_active'][$i] = 1;
						
						foreach($_REQUEST['value'] as $gid=>$value)
                        {
                            //echo($avid).'<br>';
							//echo($value).'<br>';
	
							if(strlen($value) > 0)
                            {
 								if (isset($_FILES['Imagen_Answer']) && !empty ($_FILES['Imagen_Answer']['name'][$i])) 
								{							
									$size = getimagesize($_FILES['Imagen_Answer']['tmp_name'][$i]);
									if ($_FILES['Imagen_Answer']['size'][$i] <= 20480 && $size['0'] <= IMAGE_ANCHO && $size['1'] <= IMAGE_ALTO)
									{
										$pos = strpos($_FILES['Imagen_Answer']['name'][$i], '.');									
										$name_total = substr($_FILES['Imagen_Answer']['name'][$i], 0, $pos);
										$extension = substr($_FILES['Imagen_Answer']['name'][$i], $pos);
										if ($extension == '.gif' || $extension == '.jpg' || $extension == '.jpeg' || $extension == '.png' || $extension == '.GIF' || $extension == '.JPG' || $extension == '.JPEG' || $extension == '.PNG') 
										{
											$file = $_FILES['Imagen_Answer']['tmp_name'][$i];
											//$newfile = $_SERVER['DOCUMENT_ROOT'].'/'.NAMEAPP.'/html_image_a/'.$avid.$extension;
											$newfile = $_SERVER['DOCUMENT_ROOT'].PUBLICAPP.'/'.NAMEAPP.'/image_grupos/'.$gid.$extension;
											
											//si la nueva imagen que esta por subir es distinta en  extension que la que tiene entonces se elimina la que tiene
											if($gid.$extension != $_REQUEST['img_path_answer_actual'][$gid])
											{ unlink('image_grupos/'.$_REQUEST['img_path_answer_actual'][$gid]); }
											
											
											if (!copy($file, $newfile)) 
											{echo "failed to copy $file...\n";}
											$input['imagen'][$i] = $gid.$extension;
											$input['img_path'][$i]  = $gid.$extension;
											
											//$input['a_active'][$i] = 1;
										    /*echo $file;
//											exit;*/
										} 
										else
										{ 
											$error .= "Image type not permmited. Please try another. ";
											//$input['a_active'][$i] = 0;
										}
									}
									else
									{ 
										$error .= "La imagen es muy grande. por favor cargue otra imagen. ";
										//$input['a_active'][$i]= 0; 
									}
											
								}				
 								//si el gid es x0, x1, etc carga en el input estos valores
								if($gid{0}=='x')
                                { $input['gid'][] = 'x' . $new_answer_count++; 
                                  
                                }
                                else								
								{ $input['gid'][] = $gid; }

                                $input['value'][] = $this->SfStr->getSafeString($value,$ss_type);

                               /* $user_image = $_REQUEST['image'][$avid];
                                $image_key = array_search($user_image,$input['allowable_images']);
                               						
								if($image_key === FALSE)
                                { $error .= 'Invalid image selection. '; }
                                else
                                {
                                    $input['image'][] = $this->SfStr->getSafeString($user_image,$ss_type);
                                    $input['image_selected'][] = array($image_key => ' selected');
                                }*/

								if(empty($_REQUEST['puntaje_min_value'][$gid]))
                                { $input['puntaje_min_value'][] = 0; }
                                else
                                { $input['puntaje_min_value'][] = (int)$_REQUEST['puntaje_min_value'][$gid]; }
                                
                                
                                if(empty($_REQUEST['puntaje_max_value'][$gid]))
                                { $input['puntaje_max_value'][] = 0; }
                                else
                                { $input['puntaje_max_value'][] = (int)$_REQUEST['puntaje_max_value'][$gid]; }
                                
                                
                                //$input['puntaje'][] = (int)$_REQUEST['puntaje'][$avid];
                                
								if (isset($_REQUEST['img_path_answer_actual'][$gid]) && !empty($_REQUEST['img_path_answer_actual'][$gid]))
								{ 	
									$input['img_path'][$i] = $_REQUEST['img_path_answer_actual'][$gid];
									//$input['a_active'][$i] = 1;
									if (($input['img_path'][$i] != $input['imagen'][$i]) && ($input['imagen'][$i] != ''))
									{
										$input['img_path'][$i] = $input['imagen'][$i];
										//$input['a_active'][$i] = 1;
									}	 
								}
								
								if(isset($_REQUEST['delete_image'][$gid]))
								{
									unlink('image_grupos/'.$input['img_path'][$i]);
									$input['img_path'][$i] = ''; 
								}		
                            }
                            else
                            {
                                
                                if(!empty($gid) && $gid{0} != 'x')
                                { $input['delete_gid'][] = (int)$gid; }
                            }
                        $i++;
						}
						
						if(count($input['value']) == 0)
                        { $error .= ' Los valores de respuesta deben ser proporcionados.'; }
           }
                    else
                    { $error .= ' Bad display value or numeric value entered.'; }

                    if(!isset($input['num_answers']))
                    { $input['num_answers'] = 4; }

					if(isset($_REQUEST['add_answers_submit']))
                    {
                        $num = (int)$_REQUEST['add_answer_num'];
                        $input['num_answers'] += $num;
                    }

                    if($input['num_answers'] > 99)
                    {
                    	
                        $input['num_answers'] = 99;
                        $error .= ' Se permiten solamente 99 valores de respuesta.';
                        $input['show_add_answers'] = FALSE;
                    }
                    elseif($input['num_answers'] == 99)
                    { $input['show_add_answers'] = FALSE; }

                    $diff = $input['num_answers'] - @count($input['value']);
	                

                    for($x=0;$x<$diff;$x++)
                    {
                        $input['gid'][] = 'x' . $new_answer_count++;
                    }

               
                    //$error .= "Incorrect Answer Type";
                
            

            if(empty($error) && !isset($_REQUEST['add_answers_submit']))
            {

                /*$query = "UPDATE {$this->CONF['db_tbl_prefix']}answer_types SET
                          type={$input['type']}
                          WHERE aid = $aid";
                $rs = $this->db->Execute($query);
		      
				if($rs === FALSE)
                { $this->error("Error updating answer: " . $this->db->ErrorMsg()); }
                else
                {*/
                    $query = array();

                    /*switch($_REQUEST['type'])
                    {
                        case 'T':
                        case 'S':
                        case 'N':
                            $query[] = "DELETE FROM {$this->CONF['db_tbl_prefix']}answer_values WHERE aid = $aid";
                        break;

                        case 'MS':
                        case 'MM':*/

                            $sql_value = '';
                            $sql_puntaje_min_value = '';
                            $sql_puntaje_max_value = '';
                            $sql_image = '';
                            $sql_gid = '';
                            $insert = array();
										
                            for($x=0;$x<$input['num_answers'];$x++)
                            {
                                if(isset($input['value'][$x]))
                                {
                                    if(substr($input['gid'][$x],0,1) == 'x')
                                    {
                                    	
                                    	
                                        $gid = $this->db->GenID($this->CONF['db_tbl_prefix'].'grupos_sequence');				
															
										$insert[] = "($gid, $sid,{$input['value'][$x]},{$input['puntaje_min_value'][$x]},{$input['puntaje_max_value'][$x]},'{$input['img_path'][$x]}')";
										
                                    }
                                    else
                                    {
                                    	$sql_value .= "WHEN gid = {$input['gid'][$x]} THEN {$input['value'][$x]} ";
                                        //$sql_numeric_value .= "WHEN avid = {$input['avid'][$x]} THEN {$input['numeric_value'][$x]} ";
                                        
                                        $sql_puntaje_min_value .= "WHEN gid = {$input['gid'][$x]} THEN {$input['puntaje_min_value'][$x]} ";
                                        $sql_puntaje_max_value .= "WHEN gid = {$input['gid'][$x]} THEN {$input['puntaje_max_value'][$x]} ";
                                        
                                        //$sql_image .= "WHEN avid = {$input['avid'][$x]} THEN {$input['image'][$x]} ";
										$sql_img_path .= "WHEN gid = {$input['gid'][$x]} THEN '{$input['img_path'][$x]}'";
										//$sql_a_active .= "WHEN avid = {$input['avid'][$x]} THEN '{$input['a_active'][$x]}'";
										//$sql_puntaje .= "WHEN avid = {$input['avid'][$x]} THEN '{$input['puntaje'][$x]}'";
                                        $sql_gid .= $input['gid'][$x] . ',';                            
										
                                    }
                                   
                                }
                            }
                             

							if(!empty($sql_gid))
                            {
                                $sql_gid = substr($sql_gid,0,-1);
                                //$query[] = "UPDATE {$this->CONF['db_tbl_prefix']}answer_values SET value = CASE $sql_value END, numeric_value = CASE $sql_numeric_value END, image = CASE $sql_image END, img_path = CASE $sql_img_path END, a_active = CASE $sql_a_active, puntaje = CASE $sql_puntaje END WHERE avid IN ($sql_avid)";
                                $query[] = "UPDATE {$this->CONF['db_tbl_prefix']}grupos SET texto = CASE $sql_value END, pmin = CASE $sql_puntaje_min_value END ,pmax = CASE $sql_puntaje_max_value END, imagen = CASE $sql_img_path END WHERE gid IN ($sql_gid)";
                            }
							
                            if(count($insert))
                            { $query[] = "INSERT INTO {$this->CONF['db_tbl_prefix']}grupos (gid, sid, texto, pmin, pmax, imagen) VALUES " . implode(',',$insert); }


                            if(count($input['delete_avid']))
                            { $query[] = "DELETE FROM {$this->CONF['db_tbl_prefix']}answer_values WHERE gid IN (" . implode(',',$input['delete_gid']) . ')'; }
                        
                            //break;
                    //}

                    
                    
                    
                    foreach($query as $q)
                    {
                        $rs = $this->db->Execute($q);
                        if($rs === FALSE)
                        { $this->error("Error actualizando grupos: " . $this->db->ErrorMsg()); }
                    }

                    $load_answer = TRUE;
                    $show['success']=TRUE;
               // }
            }
           
           
            $this->smarty->assign_by_ref('answer',$input);
            if(empty($error) && !isset($_REQUEST['add_answers_submit'])){
              $this->setMessageRedirect("encuesta_puntaje.php?sid=$sid");
		      $this->setMessage('&nbsp;','Se Hicieron los cambios correctamente',1);
            }
            
        }

        if($load_answer)
        {
        	$query = "SELECT gid, sid, texto, pmin, pmax, imagen FROM {$this->CONF['db_tbl_prefix']}grupos WHERE sid = $sid ORDER BY gid ASC";      	
            $rs = $this->db->Execute($query);
        	if($rs === FALSE)
            { $this->error("Error obteniendo grupos: " . $this->db->ErrorMsg()); return;}
            else
            {
              while($r = $rs->FetchRow($rs))
              {
              	$answer['gid'][] = $r['gid'];
              	$answer['value'][] = $this->SfStr->getSafeString($r['texto'],SAFE_STRING_TEXT);
                $answer['puntaje_min_value'][] = $r['pmin'];
                $answer['puntaje_max_value'][] = $r['pmax'];
                
                $answer['img_path'][] = $r['imagen'];
                
               // $key = array_search($r['image'],$answer['allowable_images']);
              //  $answer['image_selected'][] = array($key => ' selected');
				
				/*$answer['a_active'][] = $r['a_active'];
				$answer['puntaje'][] = $r['puntaje'];*/
			  }
			  
			   $answer['num_answers'] = count($answer['gid']); 
			    
			   if($answer['num_answers'] < 99)
               { $answer['show_add_answers'] = TRUE; }     
              
               $this->smarty->assign_by_ref('answer',$answer);  	
            }
            
        	
            
            /*$query = "SELECT aid, type, sid FROM {$this->CONF['db_tbl_prefix']}answer_types WHERE aid = $aid AND name = 'Default'";
            $rs = $this->db->Execute($query);
            if($rs === FALSE)
            { $this->error("Error selecting answer type information: " . $this->db->ErrorMsg()); return;}
            if($r = $rs->FetchRow($rs))
            {		
				$answer = array();
                $answer = $r;
               

                $answer['selected'][$r['type']] = ' selected';
                $answer['allowable_images'] = $input['allowable_images'];

                $query = "SELECT avid, value, numeric_value, image, img_path, a_active, puntaje FROM {$this->CONF['db_tbl_prefix']}answer_values WHERE aid = $aid ORDER BY avid ASC";
               
                $rs = $this->db->Execute($query);
                if($rs === FALSE)
                { $this->error('Error getting answer values: ' . $this->db->ErrorMsg()); return;}
                if($r = $rs->FetchRow($rs))
                {
                    do{
                        $answer['avid'][] = $r['avid'];
                        $answer['value'][] = $this->SfStr->getSafeString($r['value'],SAFE_STRING_TEXT);
                        $answer['numeric_value'][] = $r['numeric_value'];
                        $key = array_search($r['image'],$answer['allowable_images']);
                        $answer['image_selected'][] = array($key => ' selected');
						$answer['img_path'][] = $r['img_path'];
						$answer['a_active'][] = $r['a_active'];
						$answer['puntaje'][] = $r['puntaje'];
						
                    }while($r = $rs->FetchRow($rs));

                    $answer['num_answers'] = count($answer['avid']);

                    if($answer['num_answers'] < 100)
                    { $answer['show_add_answers'] = TRUE; }
                }
                else
                {
                    $answer['num_answers'] = 6;
                    for($x=0;$x<$answer['num_answers'];$x++)
                    { $answer['avid'][] = "x$x"; }
                    $answer['show_add_answers'] = TRUE;
                }

                $this->smarty->assign_by_ref('answer',$answer);
            }
            else
            { $error = "Invalid answer type"; }*/
        }

        if(!empty($error))
        {
           

            $count = 0;
            foreach($_REQUEST['value'] as $key=>$value)
            {
            	$input['value'][$count] = $this->SfStr->getSafeString($value,SAFE_STRING_TEXT);
                $input['puntaje_min_value'][$count]=(int)$_REQUEST['puntaje_min_value'][$key];
                $input['puntaje_max_value'][$count]=(int)$_REQUEST['puntaje_max_value'][$key];
                
                /*$input['value'][$count] = $this->SfStr->getSafeString($value,SAFE_STRING_TEXT);
                $input['numeric_value'][$count] = $this->SfStr->getSafeString($_REQUEST['numeric_value'][$key],SAFE_STRING_TEXT);
                $input['image_selected'][$count][$_REQUEST['image'][$key]] = ' selected';*/
		        $count++;
            }
            
            //$error .= ' las dimensiones de la imagen no cumple con el formato establecido.';
			$this->puntaje_error($error,"encuesta_puntaje.php?sid=$sid",'Error',2);
            
			//$show['error'] = $error;
        }
        
        
        /******************TIPO DE ENCUESTA**********************************************************************/
        $query = "SELECT tipo FROM {$this->CONF['db_tbl_prefix']}surveys WHERE sid=$sid";				  						
        $rs = $this->db->Execute($query);

        if($rs === FALSE)
        { $this->error("Error obteniendo el tipo de encuesta: " . $this->db->ErrorMsg()); }
        else
        {  
           $r = $rs->FetchRow($rs);
           $data['tipo'] = $r['tipo'];
        }
        /*********************************************************************************************************/
        
         
        $data['sid'] = $sid;
		//$data['qid'] = $input['qid'];
		//$data['aid'] = $input['aid'];
        $this->smarty->assign_by_ref('data',$data);
        //$this->smarty->assign_by_ref('show',$show);
                
        $data['links'] = $this->smarty->Fetch($this->template.'/edit_survey_links.tpl');
       
        $retval = $this->smarty->Fetch($this->template.'/encuesta_puntaje.tpl');

        return $retval;
		
  }

 
  
  
  function nuevos_grupos($sid)
    {
        $error = '';

		//Ensure user is logged in with valid privileges
        //for the requested survey or is an administrator
        if(!$this->_CheckLogin("new_answer_type.php?sid=$sid"))
        { return $this->showLogin('edit_survey.php',array('sid'=>$sid)); }

        //The following values are also set
        //upon a successful submission to "reset"
        //the form...
        //$input['name'] = '';
        $input['active'] = '0';
        $input['value'] = array();
        //$input['numeric_value'] = array();
        $input['num_answers'] = 4;
        $input['show_add_answers'] = TRUE;
        $input['sid'] = (int)$sid;
		$input['qid'] = (int)$qid;
        //$input['allowable_images'] = $this->get_image_names();
		$input['img_path'] = '';
		
        $query = "SELECT tipo FROM {$this->CONF['db_tbl_prefix']}surveys WHERE sid=$sid";
        
        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error('error al obtener el tipo de encuesta: ' . $this->db->ErrorMsg()); return; }
        elseif($r = $rs->FetchRow($rs))
        { $data['tipo'] = $r['tipo']; }	
        
        $data['puntajeMin'] = $this->puntaje_min_max('min',$input['sid']);
        $data['puntajeMax'] = $this->puntaje_min_max('max',$input['sid']);
        	

        
        if(isset($_REQUEST['submit']) || isset($_REQUEST['add_answers_submit']))
        {  
        	if(isset($_REQUEST['add_answers_submit']))
            { $ss_type = SAFE_STRING_TEXT; }
            else
            { $ss_type = SAFE_STRING_DB; }

            /*if(strlen($_REQUEST['name']) > 0)
            { $input['name'] = $this->SfStr->getSafeString($_REQUEST['name'],$ss_type); }
            else
            { $error .= 'Please enter a name. '; }*/

            //if($_REQUEST['active'] == "0")
	        //{$input['active'] = "0";}
			//echo var_dump($_REQUEST);
			//exit;*/

                  //$input['type'] = $this->SfStr->getSafeString($_REQUEST['type'],$ss_type);

            if(isset($_REQUEST['value']) && is_array($_REQUEST['value']) &&
               isset($_REQUEST['puntaje_min_value']) && is_array($_REQUEST['puntaje_min_value']) &&
               isset($_REQUEST['puntaje_max_value']) && is_array($_REQUEST['puntaje_max_value']) &&
               count($_REQUEST['value']) <= 99)
            {

            	       $input['num_answers'] = min(99,count($_REQUEST['value']));

                        foreach($_REQUEST['value'] as $key=>$value)
                        { 
                        	
                            if(strlen($value) > 0)//aqui carga los valores
                            {   
                                $input['value'][] = $this->SfStr->getSafeString($value,$ss_type);
                                $input['puntaje_min_value'][]=(int)$_REQUEST['puntaje_min_value'][$key];
                                $input['puntaje_max_value'][]=(int)$_REQUEST['puntaje_max_value'][$key];

                                
                                
                                /*$image_key = array_search($_REQUEST['image'][$key],$input['allowable_images']);
                                if($image_key === FALSE)
                                { $error .= 'Nombre de Imagen no valido. '; }
                                else
                                {
                                    $input['image'][] = $this->SfStr->getSafeString($_REQUEST['image'][$key],$ss_type);
                                    $selected['image'][] = array($image_key => ' selected');
								}*/
                                
                                /*if(empty($_REQUEST['numeric_value'][$key]))
                                { $input['numeric_value'][] = 0; }
                                else
                                { $input['numeric_value'][] = (int)$_REQUEST['numeric_value'][$key];  }*/
																				
                            }
                        }
                        
                        if(count($input['value']) == 0 && isset($_REQUEST['submit']))
                        { $error .= ' Los valores de respuesta deben ser proporcionados.'; }
                    }
                    else
                    {$error .= ' Bad display answer value or numeric value was entered.'; }

                    if(!isset($input['num_answers']))
                    { $input['num_answers'] = 4; }

                    if(isset($_REQUEST['add_answers_submit']))
                    { $input['num_answers'] += (int)$_REQUEST['add_answer_num']; }

                    if($input['num_answers'] > 99)
                    {
                        $input['num_answers'] = 99;
                        $error .= 'se permiten solamente 99 valores de respuesta.';
                        $input['show_add_answers'] = FALSE;
                    }
                    elseif($input['num_answers'] == 99)
                    { $input['show_add_answers'] = FALSE; }

         
      
            if(!isset($_REQUEST['add_answers_submit']) && (!isset($error) || strlen($error) == 0))
            {  

                /*$aid = $this->db->GenID($this->CONF['db_tbl_prefix'].'answer_types_sequence');
                $query = "INSERT INTO {$this->CONF['db_tbl_prefix']}answer_types (aid, type, sid, active) VALUES
                          ($aid, {$input['type']},{$input['sid']},{$input['active']})";				  						
                $rs = $this->db->Execute($query);

                if($rs === FALSE)
                { $this->error("Error inserting new answer: " . $this->db->ErrorMsg()); }*/
                /*else
                {*/
                    if($c = count($input['value']))
                    {
                        $sql = '';
                        
                        

                        for($x=0;$x<$c;$x++)
                        {
					 		//$input['a_active'][$x] = 1;							
							//$gid += $x;
							$gid = $this->db->GenID($this->CONF['db_tbl_prefix'].'grupos_sequence');
							
							/*$query = "INSERT INTO {$this->CONF['db_tbl_prefix']}grupos (gid) VALUES('{$gid}')";
                            $rs = $this->db->Execute($query);
                            if($rs === FALSE)
                            {
                              $this->error("Error generando ids: " . $this->db->ErrorMsg());
                              //$this->db->Execute("DELETE FROM {$this->CONF['db_tbl_prefix']}grupos WHERE gid = $gid");
                            }*/
                            
							if (isset($_FILES['Imagen_Answer']) && !empty ($_FILES['Imagen_Answer']['name'][$x])) 
								{
									
									$size = getimagesize($_FILES['Imagen_Answer']['tmp_name'][$x]);
								
									if ($_FILES['Imagen_Answer']['size'][$x] <= 20480 && $size['0'] <= IMAGE_ANCHO && $size['1'] <= IMAGE_ALTO)
									{
										$pos = strpos($_FILES['Imagen_Answer']['name'][$x], '.');									
										$name_total = substr($_FILES['Imagen_Answer']['name'][$x], 0, $pos);
										$extension = substr($_FILES['Imagen_Answer']['name'][$x], $pos);
										if ($extension == '.gif' || $extension == '.jpg' || $extension == '.jpeg' || $extension == '.png' || $extension == '.GIF' || $extension == '.JPG' || $extension == '.JPEG' || $extension == '.PNG')
										{
											$file = $_FILES['Imagen_Answer']['tmp_name'][$x];
											//$newfile = $_SERVER['DOCUMENT_ROOT'].'/'.NAMEAPP.'/html_image_a/'.$avid.$extension;
											$newfile = $_SERVER['DOCUMENT_ROOT'].PUBLICAPP.'/'.NAMEAPP.'/image_grupos/'.$gid.$extension;

											if (!copy($file, $newfile)) 
											{echo "failed to copy $file...\n";}
											$input['img_path'][$x] = $gid.$extension;
											//$input['a_active'][$x] = 1;
										} 
										else
										{ 
											//$input['a_active'][$x] = 0;
                                            //$input['img_path'][$x]='';
                                            $this->db->Execute("DELETE FROM {$this->CONF['db_tbl_prefix']}grupos WHERE gid = $gid");
                                            $error .= ' solo se permite imagenes: .gif .jpg .jpeg .png .GIF .JPG .JPEG .PNG';
										    $this->puntaje_error($error,"encuesta_puntaje.php?sid=$sid",'Error',2);
										}
										
									}
									else
									{ 
										//$input['a_active'][$x]= 0; 
									    //$input['img_path'][$x]='';
									    $this->db->Execute("DELETE FROM {$this->CONF['db_tbl_prefix']}grupos WHERE gid = $gid");
									    $error .= ' las dimensiones de la imagen no cumple con el formato establecido.';
									    $this->puntaje_error($error,"encuesta_puntaje.php?sid=$sid",'Error',2);
									}
									
								}

                            $sql .= "($gid,$sid,{$input['value'][$x]},{$input['puntaje_min_value'][$x]},{$input['puntaje_max_value'][$x]},'{$input['img_path'][$x]}'),";
                       }
                       
                        
                        $query = "INSERT INTO {$this->CONF['db_tbl_prefix']}grupos (gid, sid, texto, pmin, pmax, imagen) VALUES " . substr($sql,0,-1);
                        
                        $rs = $this->db->Execute($query);
                        if($rs === FALSE)
                        {
                            $this->error("Error insertando grupos: " . $this->db->ErrorMsg());
                            $this->db->Execute("DELETE FROM {$this->CONF['db_tbl_prefix']}grupos WHERE gid = $gid");
                        }
                        else
                        {
                           $this->setMessageRedirect("encuesta_puntaje.php?sid=$sid");
		                   $this->setMessage('&nbsp;','Grupos Agregados satisfactoriamente',MSGTYPE_NOTICE); 	
                        }
						/*else
						{
							$this->db->Execute("UPDATE {$this->CONF['db_tbl_prefix']}questions SET aid = $aid WHERE qid = $qid");
						}*/
                    }
                   
                   /* if( $_REQUEST["cbas"] == 1 )
                    {   
                      $this->setMessageRedirect('index.php');
					  $this->setMessage('&nbsp;','Respuesta agregada correctamente.',MSGTYPE_NOTICE);
                    }*/
                    /*elseif($input['a_active']['1'] == 1)
					{   
						$success=TRUE;
                    	$this->smarty->assign('success',$success);
						$this->setMessageRedirect('question_edit_survey.php?sid='.$input['sid'].'&mode=questions&qid=$qid');
						$this->setMessage('&nbsp;','Respuesta agregada correctamente',MSGTYPE_NOTICE);
					}*/
					/*else
					{
					    $success=TRUE;
                    	$this->smarty->assign('success',$success);
						$this->setMessageRedirect('question_edit_survey.php?sid='.$input['sid'].'&mode=questions&qid=$qid');
						$this->setMessage('&nbsp;','Respuesta agregada correctamente.',MSGTYPE_NOTICE);
					}*/
							
                    /*$allowable_images = $input['allowable_images'];
                    $input = array();
                    //$input['name'] = '';
					$input['active'] = '';
                    $input['value'] = array();
                    $input['numeric_value'] = array();
                    $input['num_answers'] = 6;
                    $input['show_add_answers'] = TRUE;
                    $input['sid'] = (int)$_REQUEST['sid'];
					$input['qid'] = (int)$_REQUEST['qid'];
                    $input['allowable_images'] = $allowable_images;*/
                //}
            }
        }

		/*$selected[$_REQUEST['type']] = ' selected';
        $this->smarty->assign('selected',$selected);*/

        if(strlen($error)>0)
        {
            //Encode $input values so they are safe to "reshow"
            //in the form in case of an error
            //$input['name'] = $this->SfStr->getSafeString($_REQUEST['name'],SAFE_STRING_TEXT);

			/*$input['active'] = 0;
            if($_REQUEST['active'] == 1)
	        {$input['active'] = 1;}*/

           /*foreach($_REQUEST['value'] as $key => $value)
            {
                $input['value'][$key] = $this->SfStr->getSafeString($value,$ss_type);
                $input['puntaje_min_value'][$key]=$this->SfStr->getSafeString($_REQUEST['puntaje_min_value'][$key],SAFE_STRING_TEXT);
                $input['puntaje_max_value'][$key]=$this->SfStr->getSafeString($_REQUEST['puntaje_max_value'][$key],SAFE_STRING_TEXT);
            }*/
           
            //MSGTYPE_NOTICE = 1
            //MSGTYPE_ERROR = 2
            $this->puntaje_error($error,"encuesta_puntaje.php?sid=$sid",'Error',2);
            
            /*$this->setMessageRedirect("encuesta_puntaje.php?sid=$sid");
		    $this->setMessage('Error',$error,MSGTYPE_ERROR); */
            //$show['error'] = $error;
        }
       
        $data['sid'] = $input['sid'];
		//$data['qid'] = $input['qid'];
	 
       
        $this->smarty->assign_by_ref('input',$input);
        $this->smarty->assign_by_ref('show',$show);
        $this->smarty->assign_by_ref('data',$data);
        
        /*if(isset($_REQUEST["cbas"]))
        {$this->smarty->assign_by_ref('cbas',$_REQUEST["cbas"]);}*/

        $data['links'] =  $this->smarty->Fetch($this->template.'/edit_survey_links.tpl');
		
        $retval = $this->smarty->fetch($this->template.'/encuesta_puntaje_nuevos.tpl');

        return $retval;
    }
    
    function puntaje_min_max($caso,$sid){
    	
    	$valor = 0;
    	if($caso == 'min'){
    	  $nameCase='minimo';	
    	}else{
    	  $nameCase='maximo';	
    	}
    	
    	/*$query = "SELECT SUM(puntaje) suma  
    	          FROM {$this->CONF['db_tbl_prefix']}answer_values 
                  WHERE puntaje IN(SELECT $caso(puntaje) 
                                   FROM {$this->CONF['db_tbl_prefix']}answer_values 
                                   WHERE aid IN(SELECT aid 
                                                FROM {$this->CONF['db_tbl_prefix']}answer_types 
                                                WHERE sid=$sid)
                                   GROUP BY aid)";*/
        
    	$query = "SELECT SUM(av.puntaje) suma 
                  FROM {$this->CONF['db_tbl_prefix']}answer_values av, (SELECT aid 
                                                                        FROM {$this->CONF['db_tbl_prefix']}answer_types 
                                                                        WHERE sid=$sid) x 
                  WHERE av.puntaje IN(
                                      SELECT $caso(puntaje) 
                                      FROM {$this->CONF['db_tbl_prefix']}answer_values 
                                      WHERE aid IN(x.aid) 
                                      GROUP BY aid
                                     ) 
                        AND av.aid IN(x.aid)";
    	

        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error("error al obtener el puntaje $nameCase de la  encuesta: " . $this->db->ErrorMsg()); return; }
        elseif($r = $rs->FetchRow($rs))
        { $valor = $r['suma']; }
    	
    	return $valor;
    }
    
    
    function puntaje_error($mensaje,$dir,$modo,$modoNum){
    	
    	$this->setMessageRedirect($dir);
		$this->setMessage($modo,$mensaje,$modoNum); 
    }

} 

?>